package com.prime.cn.realm;

import com.prime.cn.pojo.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashSet;
import java.util.Set;

public class MyRealm extends AuthorizingRealm {
    //授权认证
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
            UsernamePasswordToken user= (UsernamePasswordToken) pc.getPrimaryPrincipal();
        SimpleAuthorizationInfo sai=new SimpleAuthorizationInfo();
        Set<String> roles=new HashSet<>();
        Set<String> permission=new HashSet<>();
        roles.add("user");
        permission.add("user:do");
        if("admin".equals(user.getUsername())){
            roles.add("admin");
            permission.add("admin:do");
        }
        sai.setRoles(roles);
        sai.setStringPermissions(permission);

        return sai;
    }
    //登录认证：
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        User userToken= tokenToUser((UsernamePasswordToken) token);
        System.out.printf(userToken.getUsername()+"|||"+userToken.getPwd());
        switch(userToken.getUsername()){
            case "admin":
                if(!userToken.getUsername().equals("admin")||!userToken.getPwd().equals("123")){
                    //账号密码正确
                    return null;
                }
            break;
            case "user":
                if(!userToken.getUsername().equals("user")||!userToken.getPwd().equals("123")){
                    //账号密码正确
                    return null;
                }
                break;
             default:
                 return null;

        }

//        Session session=SecurityUtils.getSubject().getSession();
//         session.setAttribute("user", userToken);
        SimpleAuthenticationInfo saif=new SimpleAuthenticationInfo(token,userToken.getPwd(),this.getName());

        return saif;
    }
    protected User tokenToUser(UsernamePasswordToken ut){
       return new User(ut.getUsername(),String.valueOf(ut.getPassword()));
    }
}
